package org.rpc.protocol;

import org.apache.commons.io.IOUtils;
import org.rpc.common.Invocation;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;

public class HttpClient {
    public String send(String hostName, Integer port, Invocation invocation) throws IOException {
        URL url = new URL("http", hostName, port, "/");
        HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
        httpURLConnection.setRequestMethod("POST");
        httpURLConnection.setDoOutput(true);
        //配置
        OutputStream outputStream = httpURLConnection.getOutputStream();
        ObjectOutputStream objectOutputStream = new ObjectOutputStream(outputStream);
        //写入数据
        objectOutputStream.writeObject(invocation);
        //发送请求,并刷新
        objectOutputStream.flush();
        //关闭链接
        objectOutputStream.close();
        //获取输入流
        InputStream inputStream = httpURLConnection.getInputStream();
        return IOUtils.toString(inputStream);
    }
}
